package org.neu.onlineparadise.utils;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.HashMap;
import java.util.Map;


/*
* 验证码发送工具
*
* */

public class sendSmsUtil {
    private String signName="网文在线";
    private String templateCode="SMS_465750764";
    private String phone;
    private String code;
    private Map<String,Object> sms=new HashMap<>();

    public sendSmsUtil(String phone, String code) {
        this.phone=phone;
        this.code = code;
    }

    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public Map<String,Object> SmsUtil() throws Exception {
        sms.put("code", code);

        Client client = sendSmsUtil.createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setTemplateParam(JSONObject.toJSONString(sms));
        RuntimeOptions runtime = new RuntimeOptions();

        SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
        //com.aliyun.teaconsole.Client.log(Common.toJSONString(resp));


        JSONObject jsonResp = JSONObject.parseObject(Common.toJSONString(resp));

        // 获取 statusCode
        int statusCode = jsonResp.getIntValue("statusCode");

        // 获取 message
        JSONObject body = jsonResp.getJSONObject("body");
        String message = body.getString("message");

        Map<String,Object> map=new HashMap<>();
        map.put("statusCode",statusCode);
        map.put("message",message);
        return map;
    }
}
